import React, { PureComponent } from 'react'


/**
 * 弹幕类型
 * RANDOM: 随机位置
 * FIXED: 固定在中间
 */
enum BarrageType {
    RANDOM = 1,
    FIXED
}
interface BarrageProps {
    fontSize?: string;
    opacity?: Number;
    barrages?: BarrageData[]
}
interface BarrageData {
    type: BarrageType;
    color: string;
    content: string;
}

export default class Barrage extends PureComponent<BarrageProps> {
    private barrageRef: React.RefObject<HTMLDivElement>
    private fontSize: string
    private opacity: number
    private contentHeight: number
    private viewWidth: number
    private viewHeight: number
    constructor(props: any) {
        super(props);
        this.fontSize = props.fontSize || "0.8rem"
        this.opacity = props.opacity || 1
        this.barrageRef = React.createRef()
    }
    private init() {
        this.refresh();

        const div = document.createElement('div')
        div.innerHTML = 'div'
        div.style.fontSize = this.fontSize

        const body = document.getElementsByTagName('body')[0]
        body.appendChild(div)
        this.contentHeight = div.offsetHeight
        body.removeChild(div)
        const { barrages } = this.props
        if (barrages) {
            for (const barrage of barrages) {
                this.send(barrage)
            }
        }
    }

    public componentDidMount() {
        this.init();
    }
    public componentWillUnmount() {
        this.clear();
    }
    /**
     * 发送弹幕
     */
    private send(barrage: BarrageData) {

    }
    /**
     * 创建弹幕元素
     */
    private createBarrageElem() {

    }

    /**
     * 刷新弹幕容器宽高
     */
    private refresh() {
        const barrageDOM = this.barrageRef.current
        this.viewWidth = barrageDOM?.offsetWidth || 100
        this.viewHeight = barrageDOM?.offsetHeight || 100
    }

    /**
     * 清除弹幕
     */
    private clear() {
        this.randomTop = 0;
        this.fixedTop = 0;
        const barrageDOM = this.barrageRef.current;
        const children = barrageDOM?.children || [];
        for (const barrage of Array.from(children)) {
            barrageDOM?.removeChild(barrage)
        }
    }

    public render() {
        const style: any = {
            position: 'relative',
            width: '100%',
            height: '100%',
            overflow: 'hidden'
        }
        return (
            <div style={style} ref={this.barrageRef} />
        )
    }
}
